package org.fnzn.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.fnzn.bean.*;
import org.fnzn.bean.fnxf.FnxfAppCustomer;
import org.fnzn.bean.fnxf.FnxfStaffReport;
import org.fnzn.bean.vo.User;
import org.fnzn.core.CommonConstant;
import org.fnzn.core.Constants;
import org.fnzn.core.Page;
import org.fnzn.core.Result;
import org.fnzn.dao.FnglCustomerMapper;
import org.fnzn.dao.FnglGradeMapper;
import org.fnzn.dao.FnglTurnoverMapper;
import org.fnzn.service.*;
import org.fnzn.service.base.AbstractService;
import org.fnzn.service.fnxf.FnxfAppCustomerService;
import org.fnzn.service.fnxf.FnxfStaffReportService;
import org.fnzn.util.CommonUtil;
import org.fnzn.util.ResultGenerator;
import org.fnzn.util.SpringUtil;
import org.fnzn.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class FnglTurnoverServiceImpl extends AbstractService<FnglTurnover> implements FnglTurnoverService {

    @Autowired(required = false)
    private FnglTurnoverMapper fnglTurnoverMapper;
    @Autowired
    private FnglCustomerService fnglCustomerService;
    @Autowired
    private FnglHouseService fnglHouseService;
    @Autowired(required = false)
    private FnglCustomerMapper fnglCustomerMapper;
    @Autowired
    private FnglStaffService fnglStaffService;
    @Autowired
    private UserRoleServiceImpl userRoleServiceImpl;
    @Autowired
    private FnglGradeService fnglGradeService;
    @Autowired(required = false)
    private FnglGradeMapper fnglGradeMapper;
    @Autowired
    private FnxfStaffReportService fnxfStaffReportService;
    @Autowired
    private FnxfAppCustomerService fnxfAppCustomerService;

    @Override
    public Result findFnglTurnover(FnglTurnover fnglTurnover, Page page) {
        if(page.getLimit()!=null&& page.getPage()!=0){
            List<FnglTurnover> list = new ArrayList<>();
            // 获取到当前登录用户所属角色
            User user = CommonUtil.getUser();
            LrdUserrole userrole = userRoleServiceImpl.findBy("userId",user.getUser_id());
            String roleId = userrole.getRoleId();
            // 根据用户手机号获取到人员信息
            FnglStaff fnglStaff = fnglStaffService.findBy("phone", user.getUser_id());
            // 如果当前是销售经理登录，那么只能看到自己项目下所有销售人员成交信息
            if(roleId.equals(Constants.MANAGER_ROLE)){
                Condition newcondition = new Condition(FnglStaff.class);
                Example.Criteria newcriteria=newcondition.createCriteria();
                newcriteria.andEqualTo("delFlag",0);
                newcriteria.andEqualTo("blamer",fnglStaff.getStaffId());
                List<FnglStaff> fnglStaffs = fnglStaffService.findByCondition(newcondition);
                // 新建一个集合
                List<String> staffList = new ArrayList();
                if(fnglStaffs!=null&&fnglStaffs.size()>0){
                    for(FnglStaff item : fnglStaffs){
                        String staffId = item.getStaffId();
                        staffList.add(staffId);
                    }
                    PageHelper.startPage(page.getPage(),page.getLimit(), true);
                    list = fnglTurnoverMapper.findFnglTurnover(fnglTurnover,staffList);
                }
            }
            // 如果当前是销售人员登录，那么只能看到自己的成交信息
            if(roleId.equals(Constants.SALESMAN_ROLE)){
                List<String> staffList = new ArrayList<>();
                String staffId = fnglStaffService.getStaffId(user.getUser_id());
                fnglTurnover.setStaffId(staffId);
                PageHelper.startPage(page.getPage(),page.getLimit(), true);
                list = fnglTurnoverMapper.findFnglTurnover(fnglTurnover,staffList);
            }
            // 如果当前是超级管理员登录
            if(roleId.equals(Constants.ADMIN_ROLE)){
                List<String> staffList = new ArrayList<>();
                PageHelper.startPage(page.getPage(),page.getLimit(), true);
                list = fnglTurnoverMapper.findFnglTurnover(fnglTurnover,staffList);
            }
            for(FnglTurnover item : list){
                if(item.getProjectType().equals(Constants.SECONDHANDHOUSE)){
                    String houseId = item.getHouseId();
                    // 根据房源id获取到房源所在小区名称+房号
                    FnglHouse fnglHouse = fnglHouseService.findById(houseId);
                    item.setHouseId(fnglHouse.getCommunityName()+""+fnglHouse.getRoomNumber());
                }
                // 如果登记楼盘和成交楼盘不一致，那么导购人就是登记人;否则导购人空着
                if(!item.getInsertProjectId().equals(item.getProjectId())){
                    item.setDirecterId(item.getStaffId());
                    item.setDirecterName(item.getStaffName());
                }
                // 通过成交客户手机号获取到报备表信息
                FnxfStaffReport fnxfStaffReport = fnxfStaffReportService.findBy("phone", item.getCustomerPhone());
                // 判断是否为空
                if(fnxfStaffReport!=null){
                    // 获取到一级报备人id
                    Integer customerId = fnxfStaffReport.getCustomerId();
                    // 根据报备人id获取到报备人名字
                    FnxfAppCustomer fnxfAppCustomer = fnxfAppCustomerService.findById(customerId);
                    // 返回一级报备人id
                    item.setStaffReportId(String.valueOf(customerId));
                    // 返回一级报备人姓名
                    item.setStaffReportName(fnxfAppCustomer.getRealName());
                    // 获取到一级报备人的电话
                    String phone = fnxfAppCustomer.getLoginId();
                    // 根据该手机号去查询报备表信息看看是否已经被报备过
                    FnxfStaffReport fnxfStaffReport1 = fnxfStaffReportService.findBy("phone", phone);
                    if(fnxfStaffReport1!=null){
                        // 存在二级报备人
                        item.setSecondstaffReportId(String.valueOf(fnxfStaffReport1.getCustomerId()));
                        // 获取到二级报备人名称
                        FnxfAppCustomer fnxfAppCustomer1 = fnxfAppCustomerService.findById(fnxfStaffReport1.getCustomerId());
                        item.setSecondstaffReportName(fnxfAppCustomer1.getRealName());
                    }
                }
            }
            page.setRows(list);
            page.setTotal(new PageInfo(list).getTotal());
            return ResultGenerator.genSuccessResult(page);
        }
        return ResultGenerator.genFailResult("查询失败");
    }

    @Override
    @Transactional
    public Result insertFnglTurnover(FnglTurnover fnglTurnover) {
        if(fnglTurnover!=null){
            fnglTurnover.setId(StringUtil.getUUID());
        }else{
            return ResultGenerator.genFailResult("成交记录为空");
        }
             fnglTurnover.setCreateTime(new Date());
             // 成交进度初始为0
             fnglTurnover.setStep("0");
             Condition condition = new Condition(FnglTurnover.class);
             Example.Criteria criteria=condition.createCriteria();
             // 根据删除状态查询列表
             criteria.andEqualTo("delFlag",0);
             List<FnglTurnover> turnoverList = findByCondition(condition);
             if(turnoverList!=null&&turnoverList.size()>0){

                 // 如果选择的是新房项目，那么去判断项目和房号是否重复
                 if(fnglTurnover.getProjectType().equals(Constants.NEWHOUSE)){
                     for(FnglTurnover item : turnoverList){
                         // 获取到所属项目和房号并且根据这俩字段判断数据是否重复录入
                         if(item.getProjectId().equals(fnglTurnover.getProjectId())&&item.getRoomNumber().equals(fnglTurnover.getRoomNumber())){
                             return ResultGenerator.genFailResult("所属项目和房号已存在!请重新录入!");
                         }
                     }
                 }
        }
                // 录入成交信息时，录入的客户信息变为已成交状态
                // 根据所属项目id和客户电话获取到客户信息
                FnglCustomer fnglcustomer = fnglCustomerMapper.getCustomers(fnglTurnover.getProjectId(), fnglTurnover.getCustomerPhone());
                if(fnglcustomer == null){
                      return ResultGenerator.genFailResult("无法找到对应项目的客户信息，添加成交记录失败");
                }
                // 获取到客户付款方式
                fnglTurnover.setPayType(fnglcustomer.getPaymentMethod());
                int n = save(fnglTurnover);
                if(n>0) {

                 // 一旦成交那么就将该条客户信息成交状态改为1
                 fnglcustomer.setTurnoverFlag(Constants.TURNOVER);
                 fnglCustomerService.update(fnglcustomer);
                 // 录入时判断是否已结算佣金，已结算才去录入绩效
                 // 如果已结算
                 if(fnglTurnover.getPaymentFlag().equals(Constants.PAID)){
                     FnglGrade fnglGrade = new FnglGrade();
                     fnglGrade.setStaffId(fnglTurnover.getStaffId());
//                     fnglGrade.setStaffName(fnglTurnover.getStaffName());
                     fnglGrade.setTurnoverId(fnglTurnover.getId());
                     // 设置已结算绩效(刚开始已结算绩效默认为0)
                     fnglGrade.setPayment("0");
                     fnglGrade.setUnpaid(fnglTurnover.getAmount());
                     fnglGrade.setCreateTime(new Date());
                     fnglGrade.setReceptCustomer("0");
                     fnglGrade.setDealCustomer("0");
                     // 设置未结算绩效(刚开始已结算绩效默认为0)
                     fnglGrade.setUnpaid(fnglTurnover.getAmount());
                     if(fnglGrade!=null){
                         fnglGrade.setId(StringUtil.getUUID());
                     }else{
                         return ResultGenerator.genFailResult("绩效记录为空");
                     }
                     // 调用绩效模块
                     FnglGradeServiceImpl fnglGradeServiceImpl = SpringUtil.getBean(FnglGradeServiceImpl.class);
                     int num = fnglGradeServiceImpl.save(fnglGrade);
                     if (num > 0) {
                         return ResultGenerator.genSuccessResult(fnglTurnover);
                     }else{
                         return ResultGenerator.genFailResult("添加绩效记录失败");
                     }
                 }else{
                     return ResultGenerator.genSuccessResult(fnglTurnover);
                 }

            }else{
                return ResultGenerator.genFailResult("添加成交记录失败");
            }
    }

    @Override
    @Transactional
    public Result updateFnglTurnover(FnglTurnover fnglTurnover) {

        if(fnglTurnover==null){
            return ResultGenerator.genFailResult("获取数据失败");
        }
        fnglTurnover.setUpdateTime(new Date());
        int n = update(fnglTurnover);
        if(n>0){
            // 先去获取该条成交记录对应的绩效记录是否已保存
            FnglGrade fnglGradeBean = fnglGradeService.findBy("turnoverId", fnglTurnover.getId());
            // 如果没有对应的绩效记录，那么就去保存绩效记录
            if(fnglGradeBean==null){
                // 如果佣金已结算
                if(fnglTurnover.getPaymentFlag().equals(Constants.PAID)){
                    FnglGrade fnglGrade = new FnglGrade();
                    fnglGrade.setStaffId(fnglTurnover.getStaffId());
//                    fnglGrade.setStaffName(fnglTurnover.getStaffName());
                    fnglGrade.setTurnoverId(fnglTurnover.getId());
                    fnglGrade.setPayment("0");
                    // 设置未结算绩效(刚开始已结算绩效默认为0)
                    fnglGrade.setUnpaid(fnglTurnover.getAmount());
                    fnglGrade.setCreateTime(new Date());
                    fnglGrade.setReceptCustomer("0");
                    fnglGrade.setDealCustomer("0");

                    if(fnglGrade!=null){
                        fnglGrade.setId(StringUtil.getUUID());
                    }else{
                        return ResultGenerator.genFailResult("绩效记录为空");
                    }
                    // 调用绩效模块
                    FnglGradeServiceImpl fnglGradeServiceImpl = SpringUtil.getBean(FnglGradeServiceImpl.class);
                    int num = fnglGradeServiceImpl.save(fnglGrade);
                    if (num > 0) {
                        return ResultGenerator.genSuccessResult("添加成功");
                    }else{
                        return ResultGenerator.genFailResult("添加绩效记录失败");
                    }
                }else{
                    return ResultGenerator.genSuccessResult("成交记录更新成功");
                }
            }else{
                // 如果已存在对应的绩效记录，那么进行如下判断
                  // 如果佣金变为未结算，那么删除掉对应的绩效记录
                  if(fnglTurnover.getPaymentFlag().equals(Constants.UNPAID)){
                      boolean d = fnglGradeMapper.deleteFnglGrade(fnglTurnover.getId());
                      if(d){
                          return ResultGenerator.genSuccessResult("佣金变为未结算，对应绩效清空");
                      }else{
                          return ResultGenerator.genFailResult("佣金变为未结算，对应绩效清空失败");
                      }
                  }else{
                      // 如果佣金变为已结算，那么恢复该条绩效数据
                      boolean d = fnglGradeMapper.recoverFnglGrade(fnglTurnover.getId());
                      if(d){
                          return ResultGenerator.genSuccessResult("佣金变为结算，对应绩效恢复");
                      }else{
                          return ResultGenerator.genFailResult("佣金变为结算，对应绩效恢复失败");
                      }
                  }


            }
        }else{
            return ResultGenerator.genFailResult("更新失败");
        }
    }

    @Override
    @Transactional
    public Result deleteFnglTurnover(String turnoverId) {

        if(StringUtil.isEmpty(turnoverId)){
            return ResultGenerator.genFailResult("数据为空，删除失败");
        }
        FnglTurnover fnglTurnover = findById(turnoverId);
        // 获取到该条成交信息中的客户电话和客户所属项目
        FnglCustomer fnglcustomer = fnglCustomerMapper.getCustomers(fnglTurnover.getProjectId(), fnglTurnover.getCustomerPhone());
        boolean flag = fnglTurnoverMapper.deleteFnglTurnover(turnoverId);
        if(flag){
            // 删除成交记录时同时清除绩效记录
            fnglGradeMapper.deleteFnglGrade(turnoverId);
            // 删除成交记录时同时把对应的客户信息成交标志改为未成交
            if(fnglcustomer!=null){
                fnglcustomer.setTurnoverFlag(Constants.UNTURNOVER);
                fnglCustomerService.update(fnglcustomer);
            }
            return ResultGenerator.genSuccessResult("删除成功");
        }else{
            return ResultGenerator.genFailResult("删除失败");
        }
    }

    @Override
    @Transactional
    public Result deleteAllFnglTurnover(String Ids) {
        if(!StringUtil.isEmpty(Ids)){

            String[] TurnoverArr = Ids.split(",");
            int n = 0;
            for(String item : TurnoverArr){
                FnglTurnover fnglTurnover = findById(item);
                // 获取到该条成交信息中的客户电话和客户所属项目
                FnglCustomer fnglcustomer = fnglCustomerMapper.getCustomers(fnglTurnover.getProjectId(), fnglTurnover.getCustomerPhone());
                boolean flag = fnglTurnoverMapper.deleteFnglTurnover(item);
                // 删除成交记录时同时清除绩效记录
                fnglGradeMapper.deleteFnglGrade(item);
                // 删除成交记录时同时把对应的客户信息成交标志改为未成交
                if(fnglcustomer!=null){
                    fnglcustomer.setTurnoverFlag(Constants.UNTURNOVER);
                    fnglCustomerService.update(fnglcustomer);
                }
                if(flag){
                    n+=1;
                }
            }
            if(n == TurnoverArr.length){
                return ResultGenerator.genSuccessResult("删除成功");
            }else{
                return ResultGenerator.genFailResult("删除失败");
            }

        }else{
            return ResultGenerator.genFailResult("删除失败");
        }
    }

    /**
     *  成交上一步下一步，进度改变，佣金改变(付款方式为分期或者按揭)
     */
    @Override
    @Transactional
    public Result nextStep(String Id,String flag) {
        FnglTurnover fnglTurnover = findById(Id);
        if(fnglTurnover!=null){
            // 判断是上一步操作还是下一步操作
            if(flag.equals(Constants.BEFORE)){
                int newStep = Integer.valueOf(fnglTurnover.getStep()) - 1;
                fnglTurnover.setStep(newStep+"");
            }else if(flag.equals(Constants.NEXT)) {
                int newStep = Integer.valueOf(fnglTurnover.getStep()) + 1;
                fnglTurnover.setStep(newStep + "");
            }
//            }else{
//                return ResultGenerator.genFailResult("保存失败");
//            }
            int n = update(fnglTurnover);
            if(n>0) {
                // 获取到成交对应的绩效记录
                FnglGrade fnglGrade = fnglGradeService.findBy("turnoverId", fnglTurnover.getId());
                if(fnglGrade!=null){
                // 定义佣金
                double payment;
                // 获取到当前成交第几步
                if (fnglTurnover.getStep().equals(Constants.FIRST_STEP)) {
                    payment = (Double.valueOf(fnglTurnover.getAmount())) * Constants.FIRST_PAY;
                } else if (fnglTurnover.getStep().equals(Constants.SECOND_STEP)) {
                    if(StringUtil.isEmpty(fnglTurnover.getAmount())){
                        return ResultGenerator.genFailResult("保存失败");
                    }
                    payment = (Double.valueOf(fnglTurnover.getAmount())) * Constants.SECOND_PAY;
                } else if (fnglTurnover.getStep().equals(Constants.THIRD_STEP)) {
                    payment = (Double.valueOf(fnglTurnover.getAmount())) * Constants.THIRD_PAY;
                } else {
                    payment = 0;
                }
                fnglGrade.setPayment(payment + "");
                fnglGrade.setUnpaid(payment + "");
                int m = fnglGradeService.update(fnglGrade);
                if (m > 0) {
                    return ResultGenerator.genSuccessResult("保存成功");
                } else {
                    return ResultGenerator.genFailResult("保存失败");
                }
            }else{
                    return ResultGenerator.genSuccessResult("保存成功");
                }
            }else{
                return ResultGenerator.genFailResult("保存失败");
            }

        }else{
            return ResultGenerator.genFailResult("保存失败，数据为空");
        }
    }

    /**
     *  成交上一步下一步，进度改变，佣金改变(付款方式为全款)
     */
    @Override
    @Transactional
    public Result nextStep1(String Id,String flag) {
        FnglTurnover fnglTurnover = findById(Id);
        if(fnglTurnover!=null){
            // 判断是上一步操作还是下一步操作
            if(flag.equals(Constants.BEFORE)){
                int newStep = Integer.valueOf(fnglTurnover.getStep()) - 1;
                fnglTurnover.setStep(newStep+"");
            }else if(flag.equals(Constants.NEXT)) {
                int newStep = Integer.valueOf(fnglTurnover.getStep()) + 1;
                fnglTurnover.setStep(newStep + "");
            }
//            }else{
//                return ResultGenerator.genFailResult("保存失败");
//            }
            int n = update(fnglTurnover);
            if(n>0) {
                // 获取到成交对应的绩效记录
                FnglGrade fnglGrade = fnglGradeService.findBy("turnoverId", fnglTurnover.getId());
                if(fnglGrade!=null){
                    // 定义佣金
                    double payment;
                    // 获取到当前成交第几步
                    if (fnglTurnover.getStep().equals(Constants.FIRST_STEP)) {
                        payment = (Double.valueOf(fnglTurnover.getAmount())) * Constants.SECOND_PAY;
                    } else if (fnglTurnover.getStep().equals(Constants.SECOND_STEP)) {
                        if(StringUtil.isEmpty(fnglTurnover.getAmount())){
                            return ResultGenerator.genFailResult("保存失败");
                        }
                        payment = (Double.valueOf(fnglTurnover.getAmount())) * Constants.THIRD_PAY;
                    } else {
                        payment = 0;
                    }
                    fnglGrade.setPayment(payment + "");
                    fnglGrade.setUnpaid(payment + "");
                    int m = fnglGradeService.update(fnglGrade);
                    if (m > 0) {
                        return ResultGenerator.genSuccessResult("保存成功");
                    } else {
                        return ResultGenerator.genFailResult("保存失败");
                    }
                }else{
                    return ResultGenerator.genSuccessResult("保存成功");
                }
            }else{
                return ResultGenerator.genFailResult("保存失败");
            }

        }else{
            return ResultGenerator.genFailResult("保存失败，数据为空");
        }
    }
}
